// pages/project_user_add/project_user_add.js
const request = require('../../utils/promise.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    projectId:0,
    createdBy:0, // 当前登录用户id
    username: '',  // 搜索框的昵称
    userArr: [
      // {id: 10001, username: '张三丰', checked: false},
      // {id: 10002, username: '李无敌', checked: false}
    ],
    limitCount:10 // 用于查询
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      projectId: options.projectId,
      createdBy: wx.getStorageSync('userId')
    });
    this.initUserCheckData();
  },

  /**
   * 页面被用户分享时执行
   */
  onShareAppMessage() {
    return {
      title: '添加项目负责人'
    }
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: '添加项目复制人'
    }
  },

  getUserData(param) {
    request.GET('/project/getProjectUserCheckDataList', param).then(res => {
      if (res.statusCode==200) {
        this.setData({
          userArr: res.data
        })
      } else {
        wx.showToast({
          title: '查询异常',
          icon: 'error',
          duration: 1500
        })
      }
    })
  },

  /**
   * 初始化用户数据，默认展示10条
   */
  initUserCheckData() {
    const param = {projectId:this.data.projectId, limitCount:this.data.limitCount}
    this.getUserData(param);
  },

  /**
   * 根据昵称请求获取用户信息
   */
  searchProjectUserData() {
    if (this.data.username.trim()=='') {
      this.initUserCheckData();
    } else {
      const param = {username: this.data.username.trim(), projectId:this.data.projectId, limitCount:this.data.limitCount}
      this.getUserData(param);
    }
  },

  /**
   * 输入框值变化
   */
  bindSearchInput(e) {
    this.setData({
      username: e.detail.value
    })
  },

  /**
   * 表单提交
   */
  formSubmit(e) {
    
    let userIds = e.detail.value.userIds;
    const param = {projectId: this.data.projectId, userIds: userIds, createdBy: this.data.createdBy}
    
    if (userIds!=null && userIds.length==0) {
      wx.showModal({
        title: '温馨提示',
        content: '请选择一个负责人进行添加',
        showCancel: false
      })
      return;
    }

    request.POST('/project/createProjectUsers', param).then(res => {
      // console.log(res)
      if (res.statusCode==200) {
        setTimeout(function() {
          wx.navigateBack({
            delta: 1,
          })
        }, 500)
      } else {
        wx.showToast({
          title: '保存异常失败',
          icon: 'error',
          duration: 1500
        })
      }
    })
  },
  
})